<?php
namespace Framework\Library\Core;

/**
 * 数据库接口类
 * @author Canvas Kent
 */
class Database{
	
	private $config = array();
	
    private $connection;
    private $result;
    
    public function __construct($config){
    	
      $this ->connection = NULL;
      $this ->result = NULL;
    
      $this ->config['host'] = $config->DbHost;
      $this ->config['port'] = $config->DbPort;
      $this ->config['user'] = $config->DbUser;
      $this ->config['pswd'] = $config->DbPswd;
      $this ->config['name'] = $config->DbName;
      
    }
    
    /**
     * 连接数据库
     * @throws Exception
     */
    private function connect(){
      
      $this ->connection = mysql_connect( $this ->config['host'].':'.$this ->config['port'],
                                          $this ->config['user'],
                                          $this ->config['pswd'] );
      if (!$this ->connection) throw new \Exception('数据库连接失败！');
      
      mysql_select_db( $this ->config['name'], $this ->connection );
      
    }
    
    /**
     * 执行SQL查询
     * @param string $sql SQL语句
     * @throws Exception
     */
    public function query( $sql ){
      
      if (!$this ->connection) $this ->connect();
      
      $this ->result = mysql_query($sql,$this ->connection);
      if (!$this->result) throw new \Exception('数据库查询失败！<br>语句：'.$sql);
      
      return $this ->result;
    
    }
    
    /**
     * 获取最近一条SQL的执行结果中所包含的记录数
     * @return NULL|number
     */
    public function numRows(){
    	
    	if (!$this ->result) return NULL;
    	
    	return mysql_num_rows($this ->result);
      
    }
    
    /**
     * 从上一个SQL执行结果中取出数据集，数据集是一个二维数组
     * @return NULL|multitype:
     */
    public function fetch(){
    	
    	if (!$this ->result) return NULL;
    	
    	$data = array();
    	do {
    		
    		$row = mysql_fetch_assoc($this ->result);
    		if ($row) array_push($data, $row);
    		
    	}
    	while ($row);
    	
    	return $data;
      
    }
    
    /**
     * 获取最近一次SQL查询所影响的记录数
     * @return number
     */
    public function affectedRows(){
    	
    	if (!$this ->connection) $this ->connect();
    	
    	return mysql_affected_rows($this ->connection);
      
    }
    
    public function insertId(){
    	
    	if (!$this ->connection) $this ->connect();
    	 
    	return mysql_insert_id($this ->connection);
    	
    }
    
    /**
     * 生成ID条件，用于Where子句
     * @param int|array $id
     * @return string
     */
    public function makeIdCondition($id){
    	
    	$id_string = '';
    	
    	if (is_array($id)) $id_string = 'IN ('.implode(',',$id).')';
    	else $id_string = '='.$id;
    	
    	return $id_string;
    	
    }

    /**
     * SQL指令安全过滤
     * @access public
     * @param string $str  SQL字符串
     * @return string
     */
    public function escapeString($str) {
    	
    	if (!$this ->connection) $this ->connect();
    	return mysql_real_escape_string($str,$this ->connection);
    	
    }
    
    public function select( $table, $condition = NULL, $order = NULL, $limit = NULL, $fields = NULL ){
    	
    	if (empty($fields)) $fields_string = '*';
    	else {
    		if (count($fields) > 1) $fields_string = '`'.implode('`,`', $fields).'`';
    		else $fields_string = '`'.$fields[0].'`';
    	}
    	
    	$sql = "SELECT $fields_string FROM `$table`";
    	if ($condition !== NULL) $sql .= " WHERE $condition";
    	if ($order !== NULL) $sql .= " ORDER BY $order";
    	if ($limit !== NULL) $sql .= " LIMIT $limit";
    	
    	$this->query($sql);
    	
    	if ($this->numRows() > 0){
    	
    		$datas = $this->fetch();
    		return $datas;
    	
    	}else return array();
    	
    }
    
    public function count( $table, $condition = NULL ){
    	
    	$sql = "SELECT count(*) as c FROM `$table`";
    	if ($condition !== NULL) $sql .= " WHERE $condition";
    	
    	$this->query($sql);
    	
    	if ($this->numRows() > 0){
    		 
    		$datas = $this->fetch();
    		return intval($datas[0]['c']);
    		 
    	}else return 0;
    	
    }
    
    public function getNow(){
    	
    	$today = getdate();
    	$datetime = $today['year'].'-'.$today['mon'].'-'.$today['mday'].' '.$today['hours'].':'.$today['minutes'].':'.$today['seconds'];
    	
    	return $datetime;
    }
    
}